package com.config.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.config.dao.ChargeConfigDao;
import com.config.entity.ChargeConfig;


@Service(value="chargeConfigService")
public class ChargeConfigServiceImpl implements ChargeConfigService{

	@Resource(name = "chargeConfigDao")
	private ChargeConfigDao chargeConfigDao;
	
	@Override
	public void save(ChargeConfig entity) {
		chargeConfigDao.save(entity);
	}

	@Override
	public void delete(int id) {
		chargeConfigDao.delete(id);
	}

	@Override
	public void update(ChargeConfig entity) {
		chargeConfigDao.update(entity);
	}

	@Override
	public ChargeConfig getChargeConfig(int id) {
		return chargeConfigDao.get(id);
	}

	@Override
	public List<ChargeConfig> findAll() {
		return chargeConfigDao.findAll();
	}
	/**
	 * 查询半小时区间电费配置方式
	 * @param currentTime
	 * @param beforeTime
	 * @return
	 */
	@Override
	public ChargeConfig findByTime(Date belongTime) {
		ChargeConfig config=null;
		config= chargeConfigDao.findByTime(belongTime);
		return config;
	}

	@Override
	public List<ChargeConfig> findByTreePage(Integer id, int start, int limit) {
		List<ChargeConfig> structure=chargeConfigDao.findByTreePage(id, start, limit);
		for(ChargeConfig e:structure){
			if(e.getIsEffective().equals("Y")){
				e.setState("open");
			}else{
				e.setState("close");
			}
			List<ChargeConfig> child=chargeConfigDao.getCharges(e.getId());
			if(child.size()>0){
				e.setChildren(child);
			}
		}
		return structure;
	}

	@Override
	public int countByTreePage(Integer id) {
		return chargeConfigDao.countByTreePage(id);
	}

	@Override
	public List<ChargeConfig> getCharges(int fatherId) {
		return chargeConfigDao.getCharges(fatherId);
	}

	@Override
	public boolean checkVertherRepeat(Integer id) {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		List<ChargeConfig> list=chargeConfigDao.getCharges(id);
		int flag=0;
		String startTime="";
		String endTime="";
		String checkEnd="";
		for(int i=0;i<list.size();i++){
			String st=sdf.format(list.get(i).getStartTime());
			String et=sdf.format(list.get(i).getEndTime());
			if(startTime==""&&endTime==""){
				startTime=st;
				endTime=et;
				checkEnd=et;
			}else{
				checkEnd=et;
				if(endTime.equals(st)){
					endTime=et;
					continue;
				}else{
					flag++;
					break;
				}
			}
		}
		
		if(flag>0){
			return false;
		}else{
			if(startTime.equals(checkEnd)){
				return true;
			}else{
				return false;
			}
		}
	}

	@Override
	public ChargeConfig getEffectiveConfig() {
		return chargeConfigDao.findChargeType();
	}
}
